// 导入数据库操作模块
const db = require('../db/index')
// uuid
const uuid = require('uuid')
// 导入 bcryptjs 这个包
const bcrypt = require('bcryptjs')
// 导入生成 Token 的包
const jwt = require('jsonwebtoken')
// 文件名编码方式为 7bit，导入模块还原 文件中文名称
const Buffer = require('buffer').Buffer

// 导入全局的配置文件
const { jwtScretKey, expiresIn } = require('../config')

//
//
// 注册新用户
exports.regUser = (req, res) => {
  const { account, password } = req.body

  const sql = `select * from master where  account=?`
  db.query(sql, account, (err, results) => {
    if (err) return res.cc(err)
    if (results.length > 0) return res.cc('用户账号被占用，请更换账号注册！')

    const id = uuid.v1()
    const ac = account
    const pwd = bcrypt.hashSync(password, 10)
    const obj = {
      id,
      account: ac,
      password: pwd,
      create_time: new Date(),
    }

    const sql = `insert into master set ?`
    db.query(sql, obj, (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('注册失败！')
      return res.cc('注册成功！', 200)
    })
  })
}

//
//
// 登录
exports.userLogin = (req, res) => {
  const { account, password } = req.body

  const sql = `select * from master where BINARY account=?`
  db.query(sql, account, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('登录失败！')

    const compareRes = bcrypt.compareSync(password, results[0].password)
    if (!compareRes) return res.cc('登录失败！')

    // 在服务器端生成 Token 的字符串
    const user = {
      id: results[0].id,
      nickname: results[0].nickname,
      avatar: results[0].avatar,
    }
    // 对用户的信息进行加密，生成 Token 字符串
    const tokenStr = jwt.sign(user, jwtScretKey, { expiresIn: expiresIn })

    return res.send({
      code: 200,
      message: '登录成功！',
      token: 'Bearer ' + tokenStr,
    })
  })
}

//
//
// 获取用户信息
exports.getUserInfo = (req, res) => {
  const { id } = req.user

  const sql = `select * from master where id=?`
  db.query(sql, id, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('获取失败！')

    results[0].password = ''

    return res.send({
      code: 200,
      message: '获取成功！',
      data: results[0],
    })
  })
}

//
//
// 修改用户信息
exports.modifyUserInfo = (req, res) => {
  const { nickname } = req.body
  const { id } = req.user

  const sql = `update master set nickname=? where id=?`
  db.query(sql, [nickname, id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('修改失败！')
    return res.cc('修改成功！', 200)
  })
}

//
//
// 更新头像
exports.updateAvatar = (req, res) => {
  const { id: masterId } = req.user
  const { originalname, filename, path: path_, size, mimetype } = req.file
  const originalFilename = Buffer.from(originalname, 'binary').toString()

  const fixedUrl = path_.replace(/\\/g, '/')
  const obj = {
    id: uuid.v1(),
    filename,
    origin_name: originalFilename,
    upload_time: new Date(),
    master_id: masterId,
    type: mimetype,
    path: fixedUrl,
    size,
  }

  const sql = `insert into uploads set ?`
  db.query(sql, obj, (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('上传文件失败！')

    const sql2 = `update master set avatar=? where id=?`
    db.query(sql2, [fixedUrl, masterId], (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('修改头像失败！')
      return res.cc('上传成功！', 200)
    })
  })
}
